<?php

/*
 * Created on May 15, 2009
 *
 * To change the template for this generated file go to
 * Window - Preferences - PHPeclipse - PHP - Code Templates
 */

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Introdution extends MY_Controller {

    function __construct() {
        parent::__construct();

        $this->load->model('introdution_model', 'news', true);
        $this->checkLogin();
        $this->checkPermission();
        $this->load->helper('form');
        $this->template->set_template('admin');
        $this->buildMenu();
        $this->template->add_js('js/jquery1.6.1.js');
        $this->template->add_js('js/ckeditor/plugins/htmlwriter/plugin.js');
    }

    function index() {
        //echo $this->config->item('language');
        //$this->main = '<div> erer erer er </div>';
        //$this->execute();
        //$this->load->view('main', '');
        $this->view();
    }

    function create() {

        $data = array();
        $data['id_introdution'] = 0;
        $data['friendly_url'] = '';
        $data['vi_name'] = '';
        $data['en_name'] = '';
        $data['vi_description'] = '';
        $data['en_description'] = '';
        $data['active'] = 1;
        $data['image'] = '';
        $data['date_add'] = '2011-09-14';
        $data['date_upd'] = '2011-09-14';

        //$data['ddlCategory'] = $this->buidDDNewsCategoryList('category', 0);
        $config['toolbar'] = array(
            array('Source', '-',
                'NewPage', 'Preview', 'Templates', '-',
                'Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-',
                'Undo', 'Redo', '-',
                'Find', 'Replace', '-',
                'SelectAll', 'RemoveFormat', '-',
                'Maximize', 'ShowBlocks'),
            '/',
            array('Bold', 'Italic', 'Underline', 'Strike', '-',
                'Subscript', 'Superscript', '-',
                'NumberedList', 'BulletedList', '-',
                'Outdent', 'Indent', 'Blockquote', '-',
                'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock', '-',
                'Link', 'Unlink', 'Anchor', '-',
                'Image', 'Flash', 'Table', 'HorizontalRule', 'SpecialChar'
            ),
            '/',
            array('Format', 'Font', 'FontSize', '-',
                'TextColor', 'BGColor')
        );

        $this->load->library('ckeditor');
        $this->load->library('ckFinder');
        $this->template->add_js('asset/ckeditor/ckeditor.js');
        $this->template->add_js('asset/ckfinder/ckfinder.js');
        //configure base path of ckeditor folder
        $this->ckeditor->basePath = base_url() . 'asset/ckeditor/';
        $this->ckeditor->config['toolbar'] = 'Full';
        $this->ckeditor->config['language'] = 'en';
        //configure ckfinder with ckeditor config
        $this->ckfinder->SetupCKEditor($this->ckeditor, 'asset/ckfinder');
        $data['config'] = $config;

        $data['error_message'] = '';
        $data['legend_text'] = lang('create_introdution');

        $this->template->parse_view('content', 'admin/introdution/create_introdution', $data);
        $this->template->render();
    }

    function edit($id) {
        $news = $this->news->getById($id);

        if (!$news) {
            redirect('admin/news/view');
        }

        $data = $news;
        if($data['active'] == 1)
            $data['checked'] = 'checked';
        else
           $data['checked'] = '';

        //$data['ddlCategory'] = $this->buidDDNewsCategoryList('category', $news->id_ncategory);
        $data['error_message'] = '';
        $data['legend_text'] = lang('edit_introdution');

        $config['toolbar'] = array(
            array('Source', '-',
                'NewPage', 'Preview', 'Templates', '-',
                'Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-',
                'Undo', 'Redo', '-',
                'Find', 'Replace', '-',
                'SelectAll', 'RemoveFormat', '-',
                'Maximize', 'ShowBlocks'),
            '/',
            array('Bold', 'Italic', 'Underline', 'Strike', '-',
                'Subscript', 'Superscript', '-',
                'NumberedList', 'BulletedList', '-',
                'Outdent', 'Indent', 'Blockquote', '-',
                'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock', '-',
                'Link', 'Unlink', 'Anchor', '-',
                'Image', 'Flash', 'Table', 'HorizontalRule', 'SpecialChar'
            ),
            '/',
            array('Format', 'Font', 'FontSize', '-',
                'TextColor', 'BGColor')
        );

        $this->load->library('ckeditor');
        $this->load->library('ckFinder');
        $this->template->add_js('asset/ckeditor/ckeditor.js');
        $this->template->add_js('asset/ckfinder/ckfinder.js');
        //configure base path of ckeditor folder
        $this->ckeditor->basePath = base_url() . 'asset/ckeditor/';
        $this->ckeditor->config['toolbar'] = 'Full';
        $this->ckeditor->config['language'] = 'en';
        //configure ckfinder with ckeditor config
        $this->ckfinder->SetupCKEditor($this->ckeditor, 'asset/ckfinder');
        $data['config'] = $config;
        $data['base_url'] = base_url();

        $this->template->parse_view('content', 'admin/introdution/create_introdution', $data);
        $this->template->render();
    }

    function uploadFile($config) {

        $this->load->library('upload', $config);
        $result = array('error' => false);

        if (!$this->upload->do_upload('file')) {
            $result['message'] = $this->upload->display_errors();
            $result['error'] = true;
        } else {
            $result['upload_data'] = $this->upload->data();
        }

        return $result;
    }

    function view() {

        $this->load->library('pagination');

        $category = $this->uri->segment(4, -1);
        $page = (int) $this->uri->segment(5);
        $config['base_url'] = $this->base_url . 'admin/introdution/view/' . $category . '/';

        $config['total_rows'] = $this->news->getCountAllAdmin();
        $config['per_page'] = NUMBER_RECORD_PER_PAGE;
        $config['uri_segment'] = 5;
        $config['first_link'] = 'First';

        $this->pagination->initialize($config);

        //$paging = $this->pagination->create_links();
        //$this->setTemplate(array ('admin/pcategory/pcategory_list.tpl'));
        //$items = $this->loadItems();
        //$items = '';
        //$pcategories = $this->pcategory->getAllByCode($code_parent, NUMBER_RECORD_PER_PAGE, $page);

        $paging = $this->pagination->create_links();

        //$this->setTemplate(array ('admin/introdution/introdution_list.tpl'));
        //$items = $this->loadItems();
        $items = '';
        $products = $this->news->getAllAdmin($page, NUMBER_RECORD_PER_PAGE, $category);
        /* $this->setTemplate(array ('admin/introdution/introdution_item.tpl'));$category);
       
          for($i = 0; $i < count($products); $i++){
          $id = $products[$i]->id_introdution;
          $name = $products[$i]->vi_name;
          $description = $products[$i]->en_name;
          $items .= eval ($this->loadTemplate('admin/introdution/introdution_item.tpl'));
          } */

        $data = array();
        $data['rows'] = $products;
        
        //$data['id_active'] = $id;
        //$data['name'] = lang('introdution');
        //$data['url'] = base_url().'about/view/';
        //return $this->load->view('left_menu', $data, true);

        $this->template->parse_view('content', 'admin/introdution/introdution_list', $data);
        $this->template->render();
        //$this->main = $this->load->view('admin/introdution/introdution_list', $data, true); //eval ($this->loadTemplate('admin/introdution/introdution_list.tpl'));
        //$this->execute();
    }

    function loadItems() {
        /* $item = '';
          $items = $this->pcategory->getAll();
          $this->setTemplate(array ('admin/pcategory/pcategory_item.tpl'));
          for($i = 0; $i < count($items); $i++){
          $id = $items[$i]->id_pcategory;
          $name = $items[$i]->vi_name;
          $description = $items[$i]->vi_description;
          $item .= eval ($this->loadTemplate('admin/pcategory/pcategory_item.tpl'));
          }

          return $item; */
    }

    function loadNewsItems($categories = null, $parent = 0, $track = array(), $style = 1, $index = 1) {
        $items = '';
        if (!$categories) {
            $categories = $this->category->getAll();
        }
        $tmp = array();
        for ($i = 0; $i < count($categories); $i++) {
            $category = $categories[$i];
            $tmp[$category->category_parent_id][$category->category_id] = $category;
        }

        if (isset($tmp[$parent])) {
            $num_record = count($tmp[$parent]);
            foreach ($tmp[$parent] as $k => $v) {
                $parent = $v->category_id;
                $category_id = $v->category_id;
                $category_name = $v->name_vi;
                if ($index % 2 == 0)
                    $class = 'class="bg"';
                else
                    $class = '';
                $items .= eval($this->loadTemplate('news_categories_item.tpl'));
                //if(in_array($v->category_id, $track))
                $index++;
                $items .=$this->loadProductItems($categories, $parent, $track, $style + 1, $index);
            }

            /* for($j = 1; $j <= count($tmp[$parent]); $j++){
              if(isset($tmp[$parent][$j])){
              $category = $tmp[$parent][$j];
              $parent = $category->category_id;
              $category_id = $category->category_id;
              $category_name = $category->name;
              if($index%2 == 0) $class = 'class="bg"';
              else $class = '';
              $items .= eval($this->loadTemplate('product_categories_item.tpl'));
              //if(in_array($v->category_id, $track))
              $index++;
              $items .=$this->loadProductItems($categories , $parent, $track, $style + 1, $index);
              }
              } */
        }
        //print_r($categories);
        return $items;
    }

    function save() {
        $txtID = (int) trim($this->input->post('txtID'));
        $txtFriendlyUrl = trim($this->input->post('txtFriendlyUrl'));

        if ($txtID > 0)
            $news = $this->news->getById($txtID);
        else {
            $news = array();
            $news['id_introdution'] = 0;
            $news['friendly_url'] = '';
            $news['image'] = '';
        }

        $this->load->helper(array('form', 'url'));

        $this->load->library('form_validation');

        if ((($txtFriendlyUrl != $news['friendly_url'] AND $txtID > 0) OR $txtID == 0) AND $txtFriendlyUrl != '') {
            $this->form_validation->set_rules('txtFriendlyUrl', 'lang:friendly_url', 'min_length[2]|max_length[120]|callback_friendly_url_check');
            //echo $txtCode.' '.$category->code; return;
        }
        //$this->form_validation->set_rules('category', 'lang:category', 'callback_select_category_check');
        //$this->form_validation->set_message('code_check', '%s is not available.');
        $this->form_validation->set_rules('txtViName', 'lang:title', 'required|min_length[2]|max_length[120]');
        //$this->form_validation->set_rules('txtEnName', 'lang:en_name', 'required|min_length[2]|max_length[120]');
        //$this->form_validation->set_rules('txtViSummary', 'lang:vi_summary', 'required|min_length[2]|max_length[200]');
        //$this->form_validation->set_rules('txtEnSummary', 'lang:en_summary', 'required|min_length[2]|max_length[200]');
        $this->form_validation->set_rules('txtViDescription', 'lang:vi_description', 'required|min_length[2]|max_length[90000]');
        //$this->form_validation->set_rules('txtEnDescription', 'lang:en_description', 'required|min_length[2]|max_length[90000]');
        //if($txtLinkRewrite!='' AND $txtLinkRewrite!=$category->link_rewrite)
        //$this->form_validation->set_rules('txtLinkRewrite', 'lang:friendly_url', 'callback_friendly_url_check');
        /* $this->form_validation->set_rules('password', 'Password', 'required');
          $this->form_validation->set_rules('passconf', 'Password Confirmation', 'required');
          $this->form_validation->set_rules('email', 'Email', 'required');
         */

        if ($news['id_introdution'] == 0 AND $txtID > 0) {
            redirect('admin/introdution/view');
            return;
        }

        $data = $news;

        $data['friendly_url'] = trim($this->input->post('txtFriendlyUrl'));
        //$news->id_ncategory'] = trim($this->input->post('category'));
        $data['vi_name'] = trim($this->input->post('txtViName'));
        $data['en_name'] = trim($this->input->post('txtEnName'));
        //$news->vi_summary = trim($this->input->post('txtViSummary'));
        //$news->en_summary = trim($this->input->post('txtEnSummary'));
        $data['vi_description'] = trim($this->input->post('txtViDescription'));
        $data['en_description'] = trim($this->input->post('txtEnDescription'));
        $data['active'] = (int) $this->input->post('active');

        if($data['active'] == 1)
            $data['checked'] = 'checked';
        else
           $data['checked'] = '';

        //$product->image = '';
        $data['date_upd'] = date('Y-m-d H:i:s', time());
        $error_message = ''; // $this->loadErrorMessage('Thong diep loi.');
        //print_r($_POST);
        $attach_image = false;
        $image_upload = array('error' => false);
        if (isset($_FILES['file']['tmp_name']) AND strlen($_FILES['file']['tmp_name']) > 0) {
            $attach_image = true;
            $image_upload = $this->upload_image('file', INTRODUTION_IMAGE_PATH /* './Data/Images/Product/' */);
            if ($image_upload['error'])
                $error_message .= $image_upload['message'];
        }

        /* if($attach_image == true AND $image_upload['error']==true){
          echo 'Not is image'; return;
          } */

        if ($this->form_validation->run() == FALSE OR ($attach_image == true AND $image_upload['error'] == true)) {

            $error_message = validation_errors() . '<br>' . $error_message;
            //$code = uniqid();
            //$this->session->set_userdata('code', $code);
             $config['toolbar'] = array(
            array('Source', '-',
                'NewPage', 'Preview', 'Templates', '-',
                'Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-',
                'Undo', 'Redo', '-',
                'Find', 'Replace', '-',
                'SelectAll', 'RemoveFormat', '-',
                'Maximize', 'ShowBlocks'),
            '/',
            array('Bold', 'Italic', 'Underline', 'Strike', '-',
                'Subscript', 'Superscript', '-',
                'NumberedList', 'BulletedList', '-',
                'Outdent', 'Indent', 'Blockquote', '-',
                'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock', '-',
                'Link', 'Unlink', 'Anchor', '-',
                'Image', 'Flash', 'Table', 'HorizontalRule', 'SpecialChar'
            ),
            '/',
            array('Format', 'Font', 'FontSize', '-',
                'TextColor', 'BGColor')
        );

        $this->load->library('ckeditor');
        $this->load->library('ckFinder');
        $this->template->add_js('asset/ckeditor/ckeditor.js');
        $this->template->add_js('asset/ckfinder/ckfinder.js');
        //configure base path of ckeditor folder
        $this->ckeditor->basePath = base_url() . 'asset/ckeditor/';
        $this->ckeditor->config['toolbar'] = 'Full';
        $this->ckeditor->config['language'] = 'en';
        //configure ckfinder with ckeditor config
        $this->ckfinder->SetupCKEditor($this->ckeditor, 'asset/ckfinder');
        $data['config'] = $config;
        
            $data['error_message'] = '<div style="color:red">' . $error_message . '</div>';
            //if()
            $data['legend_text'] = $txtID > 0 ? lang('edit_introdution') : lang('create_introdution');
           $this->template->parse_view('content', 'admin/introdution/create_introdution', $data);
           $this->template->render();
            return;
        } else {
            //$this->load->model('pcategory_model', 'pcategory', true);
            //$cat = $this->pcategory->getByCode($product->code_pcategory);
            //$product->id_pcategory = $cat->id_pcategory;
            if ($attach_image) {
                $file_path = INTRODUTION_IMAGE_PATH . $image_upload['upload_data']['file_name'];
                if ($txtID > 0 AND $news->image != $file_path) {
                    @unlink($news->image);
                }

                $data['image'] = $file_path;
            }
            
            if ($txtID > 0) {
               
                $result = $this->news->update($data);
               //  return;
            } else {

                $data['date_add'] = date('Y-m-d H:i:s', time());
                $result = $this->news->create($data);
            }

            if (isset($_SESSION['fck_images']) AND count($_SESSION['fck_images']) > 0) {
                if ($txtID > 0)
                    $news_id = $txtID;
                else
                    $news_id = $result;
                $fck_files = array();
                for ($i = 0; $i < count($_SESSION['fck_images']); $i++) {
                    $file_url = '.' . substr($_SESSION['fck_images'][$i], strlen('/caney/' /* Replace */) - 1);

                    if (file_exists($file_url)) {
                        $fck_file = new stdClass();
                        $fck_file->file_url = $file_url;
                        $fck_file->item_id = $news_id;
                        $fck_file->type = 'introdution';
                        $fck_files[] = $fck_file;
                    }
                }

                if (count($fck_files) > 0) {
                    $this->load->model('fck_files_model', 'fckfile', true);
                    $this->fckfile->create($fck_files);
                    $_SESSION['fck_images'] = null;
                }

                //print_r($_SESSION['fck_images']);
            }

            redirect('admin/introdution/view');
        }
    }

    function upload_image($field_name, $path) {
        $result = array();
        $config['upload_path'] = $path; //'./Data/Images/';
        $config['allowed_types'] = 'gif|jpg|png|jpeg';
        //$config['max_size']	= '1000';
        //$config['max_width']  = '1024';
        //$config['max_height']  = '768';
        $config['overwrite'] = true;


        $this->load->library('upload', $config);

        if (!$this->upload->do_upload($field_name)) {
            //$error = array('error' => $this->upload->display_errors());
            $result['error'] = true;
            $result['message'] = $this->upload->display_errors();
            //$this->load->view('upload_form', $error);
        } else {
            //$data = array('upload_data' => $this->upload->data());
            $result['error'] = false;
            $result['upload_data'] = $this->upload->data();
        }

        return $result;
    }

    function code_check($code) {
        $result = $this->product->getByCode($code);
        if ($result != null) {
            $this->form_validation->set_message('code_check', '%s is not available.');
            return FALSE;
        } else {
            return TRUE;
        }
    }

    function friendly_url_check($url) {
        $result = $this->news->getByFriendlyUrl($url);
        if ($result != null) {
            $this->form_validation->set_message('friendly_url_check', '%s is not available.');
            return FALSE;
        } else {
            return TRUE;
        }
    }

    function select_category_check($cat_id) {

        if (intval($cat_id) == 0) {
            $this->form_validation->set_message('select_category_check', lang('none_selected_category'));
            return FALSE;
        } else {
            return TRUE;
        }
    }

    function testGetFile() {
        $config = array(
            'allowed' => array('JPEG', 'jpg', 'PNG', 'png', 'GIF', 'gif'),
            'max_size' => 1024000000 /* 1Mb */
        );

        $result = getFile($config, 'Data', 'http://images8.dantri.com.vn/ThumbImages/Uploaded/2009/05/08/lut080520094_327.jpg');

        if (!$result['error'])
            echo 'Get file success.';
        else
            echo $result['message'];
    }

    function delete() {
        $id = intval($this->uri->segment(4));
        $ids = array();
        if ($id > 0) {
            $ids[] = $id;
            //$this->product->delete($id);
        } else {
            if (($this->input->post('submitDelcategory'))) {
                $ids = $this->input->post('categoryBox');
            }
        }

        if (count($ids)) {
            // Xoa file anh chinh:
            $this->load->model('fck_files_model', 'fckfile', true);
            $newses = $this->news->getAllByIds($ids);
            $main_images = array();
            $fck_images = array();
            $fck_images_id = array();
            if (count($newses) > 0) {
                for ($i = 0; $i < count($newses); $i++) {
                    $main_images[] = $newses[$i]->image;
                    $_fck_files = $this->fckfile->getAllByItemId($newses[$i]->id_news, 'introdution');
                    if (count($_fck_files) > 0) {
                        for ($j = 0; $j < count($_fck_files); $j++) {
                            $fck_images[] = $_fck_files[$j]->file_url;
                            $fck_images_id[] = $_fck_files[$j]->id;
                        }
                    }
                }
            }


            //Xoa san pham
            $result = $this->news->delete($ids);
            if ($result) {
                if (count($main_images) > 0) {
                    for ($i = 0; $i < count($main_images); $i++) {
                        @unlink($main_images[$i]);
                    }
                }

                if (count($fck_images) > 0) {
                    for ($i = 0; $i < count($fck_images); $i++) {
                        @unlink($fck_images[$i]);
                    }
                }
                if (count($fck_images_id) > 0)
                    $this->fckfile->delete($fck_images_id);
            }
        }

        redirect('admin/introdution');
    }
    
    function change_order() {
        $id1 = (int) $this->uri->segment(4);
        $id2 = (int) $this->uri->segment(5);

        $cat1 = $this->news->getById($id1);
        $cat2 = $this->news->getById($id2);

        if ($cat1 AND $cat2) {
            $position1 = $cat1['position'];
            $cat1['position'] = $cat2['position'];
            $cat2['position'] = $position1;

            $this->news->update($cat1);
            $this->news->update($cat2);
        }

        redirect('admin/introdution');
    }

}

?>
